﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using PocketGPW.PocketGPWDataSetTableAdapters;

namespace PocketGPW
{
    public partial class StockViewer : Form
    {
        private PocketGPWDataSet _ds;
        private StocksTableAdapter _taStocks;
        private AlertsTableAdapter _taAlerts;
        private string _stockId;
        private bool _chartDownloaded;

        public StockViewer(PocketGPWDataSet ds, StocksTableAdapter taStocks, string stockId)
        {
            InitializeComponent();

            Icon = Properties.Resources.Icon;

            _ds = ds;
            _taStocks = taStocks;
            _stockId = stockId;

            _taAlerts = new AlertsTableAdapter();
            _taAlerts.ClearBeforeFill = true;
            _taAlerts.Fill(_ds.Alerts);

            DataRow dr = _ds.Stocks.FindByStockId(_stockId);
            if (dr == null)
                Close();

            // info
            _lblName.Text = dr["Name"].ToString();
            _lblOpen.Text += " " + dr["Open"];
            _lblLast.Text += " " + dr["Last"];
            _lblChange.Text += " " + dr["Change"] + "%";
            _lblTime.Text += " " + dr["Time"];
            _lblLow.Text += " " + dr["Low"];
            _lblHigh.Text += " " + dr["High"];
            _lblTurnoverValue.Text += " " + dr["TurnoverValue"];
            _lblVolume.Text += " " + dr["Volume"];

            _lblTurnoverValue.Visible = (dr["TurnoverValue"] != DBNull.Value);
            _lblVolume.Visible = (dr["Volume"] != DBNull.Value);

            // note
            _tbNote.Text = dr["Note"].ToString();

            // alarmy
            _cbAlertParameter.SelectedIndex = 0;
            _cbAlertComparision.SelectedIndex = 0;

            // fill list
            FillAlerts();
        }

        private void FillAlerts()
        {
            _lvAlerts.Items.Clear();

            EnumerableRowCollection<PocketGPWDataSet.AlertsRow> alerts = _ds.Alerts.Where(adr => adr["StockId"].ToString() == _stockId);
            foreach (PocketGPWDataSet.AlertsRow alert in alerts)
            {
                ListViewItem lvi = new ListViewItem(new string[] { alert["Parameter"].ToString(), alert["Comparision"].ToString(), alert["Value"].ToString() });
                lvi.Tag = alert["StockId"]; // klucz

                _lvAlerts.Items.Add(lvi);
            }
        }

        private void _miOk_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void _btnNoteSave_Click(object sender, EventArgs e)
        {
            _ds.Stocks.FindByStockId(_stockId)["Note"] = _tbNote.Text;
            _taStocks.Update(_ds.Stocks);
        } 

        private void _btnNoteRemove_Click(object sender, EventArgs e)
        {
            _tbNote.Text = String.Empty;

            _ds.Stocks.FindByStockId(_stockId)["Note"] = String.Empty;
            _taStocks.Update(_ds.Stocks);
        }

        private void _btnAlertAdd_Click(object sender, EventArgs e)
        {
            try
            {
                Convert.ToSingle(_tbAlertValue.Text);
            }
            catch 
            {
                MessageBox.Show("Wartość musi być poprawną liczbą rzeczywistą.", "Pocket GPW", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
                return;
            }

            DataRow newRow = _ds.Alerts.NewAlertsRow();
            newRow["StockId"] = _stockId;
            newRow["Parameter"] = _cbAlertParameter.SelectedItem.ToString();
            newRow["Comparision"] = _cbAlertComparision.SelectedItem.ToString();
            newRow["Value"] = Convert.ToSingle(_tbAlertValue.Text);

            _ds.Alerts.Rows.Add(newRow);
            _taAlerts.Update(_ds.Alerts);

            FillAlerts();
        }

        private void _btnAlertRemove_Click(object sender, EventArgs e)
        {
            if (_lvAlerts.SelectedIndices.Count <= 0)
                return;

            ListViewItem lvi = _lvAlerts.Items[_lvAlerts.SelectedIndices[0]];

            PocketGPWDataSet.AlertsRow dr = _ds.Alerts.Where(
                adr => adr["StockId"].ToString() == lvi.Tag.ToString() 
                &&
                adr["Parameter"].ToString() == lvi.SubItems[0].Text 
                &&
                adr["Comparision"].ToString() == lvi.SubItems[1].Text 
                &&
                adr["Value"].ToString() == lvi.SubItems[2].Text
                ).FirstOrDefault();
            if (dr == null)
                return;

            _ds.Alerts.RemoveAlertsRow(dr);
            _taAlerts.Update(_ds.Alerts);

            FillAlerts();
        }

        private void _lvAlerts_SelectedIndexChanged(object sender, EventArgs e)
        {
            _btnAlertRemove.Enabled = (_lvAlerts.SelectedIndices.Count > 0);
        }

        private void _tc_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (_tc.SelectedIndex == 3 && !_chartDownloaded)
                ThreadPool.QueueUserWorkItem(new WaitCallback(DownloadChart));
        }

        private void DownloadChart(object state)
        {
            _chartDownloaded = true;

            long timestamp = ((long)TimeSpan.FromTicks(DateTime.UtcNow.Ticks - DateTime.Parse("1970-01-01").Ticks).TotalSeconds);
            Image img = ImageHelper.FromUri(new Uri(String.Format("http://m.gpw.pl/html/cache/mcharts/{0}.png?t={1}", _stockId, timestamp.ToString())));

            try
            {
                if (img == null)
                    BeginInvoke(new Action(DownloadChartError));
                else
                    BeginInvoke(new Action<Image>(DownloadChartSuccess), new object[] { img });
            }
            catch { }
        }

        private void DownloadChartError()
        {
            MessageBox.Show("Wykres chwilowo niedostępny. Proszę spróbować ponownie później.", "Pocket GPW", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);

            _chartDownloaded = false;
        }

        private void DownloadChartSuccess(Image chart)
        {
            _pb.Image = chart;
        }
    }
}